from fastapi import APIRouter, HTTPException, Depends
from typing import List
from sqlalchemy.orm import Session
from schema import User_Farm_schema
from controller import User_Farm_controller
from database.db_init import get_db


router = APIRouter()


@router.post("/User_Farm", response_model=User_Farm_schema.User_farm, tags=["User_Farm"])
async def create_User_Farm(User_Farm: User_Farm_schema.User_farm, db: Session = Depends(get_db)):
    return User_Farm_controller.create_User_Farm(db, User_Farm)


@router.get("/User_Farm/{ID}", response_model=User_Farm_schema.User_farm, tags=["User_Farm"])
async def get_User_Farm(ID: int, db: Session = Depends(get_db)):
    db_User_Farm = User_Farm_controller.get_User_Farm(db, ID)
    if db_User_Farm is None:
        raise HTTPException(status_code=404, detail="User_Farm not found")
    return db_User_Farm


@router.get("/User_Farm", response_model=List[User_Farm_schema.User_farm], tags=["User_Farm"])
async def get_all_User_Farm(db: Session = Depends(get_db)):
    all_db_User_Farm = User_Farm_controller.get_all_User_Farm(db)
    if all_db_User_Farm is None:
        raise HTTPException(status_code=404, detail="0 User_Farm found, empty table")
    return all_db_User_Farm


@router.put("/User_Farm/{ID}", tags=["User_Farm"])
async def update_User_Farm(ID: int, field_name: str, field_value: str, db: Session = Depends(get_db)):
    try:
        db_User_Farm = User_Farm_controller.update_User_Farm(db, ID, field_name, field_value)
        if db_User_Farm is None:
            raise HTTPException(status_code=404, detail="User_Farm not found")
        return db_User_Farm
    except ValueError as error:
        raise HTTPException(status_code=400, detail=str(error))


@router.delete("/User_Farm/{ID}", tags=["User_Farm"])
async def delete_User_Farm(ID: int, db: Session = Depends(get_db)):
    is_deleted = User_Farm_controller.delete_User_Farm(db, ID)
    if is_deleted is None:
        raise HTTPException(status_code=404, detail=f'Sample {ID} does not exist in database')
    else:
        return {'message': f'Successfully delete sample {ID}'}
